package com.example.mybatislearning.config;

import com.example.mybatislearning.mymapper.HelloTest;
import com.example.mybatislearning.test.annotation.MyLearning;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.boot.autoconfigure.AutoConfigurationPackages;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.env.Environment;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.util.StringUtils;

import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.List;

public class TestMapperConfiguredMapperScannerRegistrar implements BeanFactoryAware, EnvironmentAware, ImportBeanDefinitionRegistrar {

    private static final Logger LOGGER = LoggerFactory.getLogger(TestMapperConfiguredMapperScannerRegistrar.class);
    private BeanFactory beanFactory;
    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        System.out.printf("AutoConfiguredTest::beanFactory......"+beanFactory);
        this.beanFactory = beanFactory;
    }

    @Override
    public void setEnvironment(Environment environment) {
        System.out.printf("AutoConfiguredTest::environment......"+environment);
    }

    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
        System.out.printf("registerBeanDefinitions::importingClassMetadata"+importingClassMetadata);
        System.out.printf("registerBeanDefinitions::registry"+registry);
        LOGGER.debug("Searching for mappers annotated with @MyLearning");
        BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(TestMapperScannerConfigurer.class);
        builder.addPropertyValue("processPropertyPlaceHolders", true);
        builder.addPropertyValue("annotationClass", MyLearning.class);
        builder.addPropertyValue("basePackage", StringUtils.collectionToCommaDelimitedString(Arrays.asList("com.example.mybatislearning.mymapper")));
        builder.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
        registry.registerBeanDefinition(TestMapperScannerConfigurer.class.getName(),builder.getBeanDefinition());
    }
}
